package com.wss.common.view.gallery;

import butterknife.Unbinder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.orhanobut.logger.Logger;
import com.wss.common.base.BaseFullScreenAbility;
import com.wss.common.base.ResourceTable;
import com.wss.common.base.mvp.BasePresenter;
import com.wss.common.bean.Event;
import com.wss.common.constants.Dic;
import com.wss.common.constants.EventAction;
import com.wss.common.utils.EventBusUtils;
import com.wss.common.utils.ToastUtils;
import com.wss.common.utils.ValidUtils;
import com.wss.common.widget.ActionBar;
import com.wss.common.widget.IconFontTextView;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.PageSlider;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.window.service.WindowManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class ImageGalleryAbility extends BaseFullScreenAbility {

    private Component titleBarLayout;
    private ActionBar actionBar;
    private PageSlider mViewPager;
    private Text tvImgCount;
    private Text tvDescribe;

    private Ability ability;

    /***
     * 图片集合
     */
    private List<ImageGallery> imageList = new ArrayList<>();
    private List<Component> mViews = new ArrayList<>();

    private int currentPosition;
    private ImageViewerAdapter mAdapter;
    /**
     * 是否是本地图片
     */
    private boolean isLocalImage;
    /**
     * 是否全屏显示
     */
    private boolean isFullScreen;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    public void onStart(Intent intent) {

        isFullScreen = getIntent().getBooleanParam(Dic.FULL_SCREEN, false);
        if (isFullScreen) {
            getWindow().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);
        }

        super.onStart(intent);

        setUIContent(ResourceTable.Layout_ability_image_gallery);
        ability = this;
        Collection<? extends ImageGallery> serializableExtra = getIntent()
                .getSerializableParam(Dic.IMAGE_LIST);
        if (serializableExtra != null) {
            imageList.addAll(serializableExtra);
        } else {
            ToastUtils.show("请先设置图片");
            terminateAbility();
        }
        isLocalImage = getIntent().getBooleanParam(Dic.IMAGE_LOCAL, false);
        currentPosition = getIntent().getIntParam(Dic.IMAGE_POSITION, 0);
        loadImage();
        mAdapter = new ImageViewerAdapter(mViews);
        mViewPager.setProvider(mAdapter);
        mViewPager.setCurrentPage(currentPosition);
        mViewPager.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSlideStateChanged(int state) {

            }

            @Override
            public void onPageChosen(int position) {
                currentPosition = position;
                setImageChangeText();
            }
        });

        if (!isFullScreen) {
            titleBarLayout.setVisibility(Component.VISIBLE);
            tvImgCount.setVisibility(Component.HIDE);
            IconFontTextView rightIcon = new IconFontTextView(context);
            Color textColor = new Color(getColor(ResourceTable.Color_color_333333));
            rightIcon.setTextColor(textColor);
            rightIcon.setTextSize(14);
            rightIcon.setValue(getString(ResourceTable.String_icon_delete));
            rightIcon.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    //删除照片发个通知出去 带上删除的position
                    ToastUtils.show(context, getString(ResourceTable.String_delete_success));
                    EventBusUtils
                            .sendEvent(new Event(EventAction.IMAGE_GALLERY_DELETE,
                                    currentPosition));
                    imageList.remove(currentPosition);
                    int size = imageList.size();
                    if (size < 1) {
                        terminateAbility();
                        return;
                    }
                    mViewPager.removeComponent(mViews.remove(currentPosition));
                    mAdapter.notifyDataChanged();
                    setImageChangeText();
                }
            });
            actionBar.setRightView(rightIcon);
            actionBar.setLeftIcon(ResourceTable.Media_ic_back_black,
                    new Component.ClickedListener() {
                        @Override
                        public void onClick(Component component) {

                        }
            });
            actionBar.setCenterTextColor(ResourceTable.Color_color_333333);
            //加粗
            actionBar.setCenterTextBold(true);
            actionBar.showBackImg(true);
        }

        setImageChangeText();
    }

    private void setImageChangeText() {
        if (isFullScreen) {
            tvImgCount.setText(String
                            .format("%s/%s",
                                    currentPosition + 1,
                                    imageList.size()));
        } else {
            actionBar.setCenterText(String
                    .format("%s/%s",
                            currentPosition + 1,
                            imageList.size()));
        }
    }

    private void loadImage() {
        for (ImageGallery imageGallery : imageList) {
            SubsamplingScaleImageView scaleImageView = new SubsamplingScaleImageView(context);
            scaleImageView.setLayoutConfig(new ComponentContainer.LayoutConfig(
                    ComponentContainer.LayoutConfig.MATCH_PARENT,
                    ComponentContainer.LayoutConfig.MATCH_PARENT
            ));
            if (isFullScreen) {
                scaleImageView.setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        terminateAbility();
                    }
                });
            }

            if (isLocalImage) {
                scaleImageView.setUrlPixelMap(imageGallery.getUrl());
            } else {
                if (!ValidUtils.isValid(imageGallery.getUrl())) {
                    return;
                }
                IOThread.getSingleThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        File downLoadFile;
                        try {
                            downLoadFile = mImageDownloader.downLoad(imageGallery.getUrl(), ability);
                            //如果图片路径不为空则开始执行
                            if (ValidUtils.isValid(downLoadFile)) {
                                getUITaskDispatcher().asyncDispatch(new Runnable() {
                                    @Override
                                    public void run() {
                                        scaleImageView.setUrlPixelMap(Uri
                                                .getUriFromFile(downLoadFile)
                                                .toString());
                                    }
                                });
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Logger.e("加载图片异常" + e.getMessage());
                        }
                    }
                });
            }
            mViews.add(scaleImageView);
        }
    }

    /**
     * 图片下载器
     */
    private ImageDownloader mImageDownloader = (url, activity) -> {
        File file = null;
        try {
            file = Glide.with(activity)
                    .load(url)
                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            Logger.e("下载图片异常" + e.getMessage());
        }
        return file;
    };
}
